package com.snail.common.dyd.hepler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.druid.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.snail.common.dyd.bean.DataSourceInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;


@Slf4j
@Data
@AllArgsConstructor
public class DataSourceHelper {

    private DruidDataSourceCreator dataSourceCreator;

    private DynamicRoutingDataSource dynamicRoutingDataSource;

    public void changeDataSource(DataSourceInfo dataSourceInfo) {
        boolean registered = registerDataSource(dataSourceInfo);
        if (!registered) {
            log.error("数据源注册失败，请检查数据源配置是否正确");
            return;
        }
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push(dataSourceInfo.getId());
    }

    public boolean registerDataSource(DataSourceInfo dataSourceInfo) {
        String dsName = dataSourceInfo.getId();
        if (StrUtil.isBlank(dsName)) {
            log.error("数据源名称为空，不进行数据源注册");
            return false;
        }
        if (hasRegistedDataSource(dsName)) {
            return true;
        }
        addDynamicDataSource(dataSourceInfo);
        log.info("成功注册数据源：{}", dsName);
        return true;
    }

    private boolean hasRegistedDataSource(String dsName) {
        return getDynamicRoutingDataSource().getDataSources().containsKey(dsName);
    }


    /**
     * 动态添加数据源 【注册mybatis动态数据源】
     *
     * @param dataSourceInfo 添加数据源数据对象
     */
    private void addDynamicDataSource(DataSourceInfo dataSourceInfo) {
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceInfo);
        dynamicRoutingDataSource.addDataSource(dataSourceInfo.getId(), dataSource);
    }


}
